package com.example.springbootthread.perpetualmotion;

import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

/**
 * @author : guorf
 * @version : v1.0
 * @description : TODO 子任务
 * @createTime : 2022/10/12 12:03
 */
public class ChildTask {

    // 线程池大小
    private final int POOL_SIZE = 3;
    // 拆分大小
    private final int SPLIT_SIZE = 2;

    private String taskName;

    protected volatile boolean terminal = false;

    public ChildTask(String taskName) {
        this.taskName = taskName;
    }

    // 优雅停机
    public void terminal() {
        terminal = true;
        System.out.println(taskName + " shut down");
    }

    // 处理数据
    private void doProcessData(List<Cat> datas, CountDownLatch latch){
        try {
            for (Cat cat : datas) {
                System.out.println(taskName + ":" + cat.getCatName() + ", ThreadName: " + Thread.currentThread().getName());
                Thread.sleep(1000L);
            }
        } catch (InterruptedException e) {
            System.out.println(e.getStackTrace());
        } finally {
            if (latch != null) {
                latch.countDown();
            }
        }
    }

    // 处理单个任务数据
    private void taskExecute(List<Cat> sourceDatas) {
        if (CollectionUtils.isEmpty(sourceDatas)) {
            return;
        }

        List<List<Cat>> splitDatas = Lists.partition(sourceDatas, SPLIT_SIZE);
        final CountDownLatch latch = new CountDownLatch(splitDatas.size());

        for (final List<Cat> datas: splitDatas) {
            ExecutorService executorService = TaskProcessUtil.getOrInitExecutor(taskName, POOL_SIZE);
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    doProcessData(datas, latch);
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            System.out.println(e.getStackTrace());
        }
    }

    // 获取永动任务数据
    private List<Cat> queryData() {
        List<Cat> datas = new ArrayList<>();
        for (int i = 0; i < 5; i ++) {
            datas.add(new Cat().setCatName("罗小黑" + i));
        }
        return datas;
    }

    // 程序执行入口
    public void doExecute() {
        int i = 0;
        while (true) {
            System.out.println(taskName + ": Cycle-" + i + "-Begin");
            List<Cat> datas = queryData();
            // 处理数据
            taskExecute(datas);
            System.out.println(taskName + ":Cycle-" + i + "-End");
            if (terminal) {
                // 只有应用关闭，才会走到这里，用于实现优雅的下线
                break;
            }
            i++;
        }
    }
}
